package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.admin.entity.AdLabel;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-02-27
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;

    //管理平台用户登录
    @Override
    public Map<String, Object> login(AdUserLoginDto adUserLoginDto) {
        //1. 在数据库AdUser
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName, adUserLoginDto.getName());
        AdUser adUser = this.getOne(queryWrapper);
        //2. 判断是否存在
        if (adUser == null) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //3. 数据库存储加密后的密码
        String password = adUser.getPassword();
        //4. 比较用户密码
        boolean b = encoder.matches(adUserLoginDto.getPassword(), password);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //5. 生成token
        String tokenExpireInMinutes = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 60);
        //6. 封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("user", BeanHelper.copyProperties(adUser, AdUserDto.class));
        map.put("token",tokenExpireInMinutes);

        return map;
    }
}
